package cn.tedu.store.config.tengxun;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
@RestController
public class TengXunMapUtil {
    /**
     * 通过腾讯地图将经纬度转成详细地址
     *
     *
     * @return
     */

    @RequestMapping ("getAddress")
    @ResponseBody
    public JSONObject getAdd(Point point) throws Exception {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + point.getLat() + "," + point.getLng() + "&key=HCVBZ-WP6KD-RSL4P-PK3DW-2JR4Z-NLFC5&get_poi=1";
        System.out.println(point);
        System.out.println(url);
        return getHttpJson(url);
    }

    public JSONObject getHttpJson(String url) throws Exception {
        try {
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            //请求成功
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //10KB的缓存
                byte[] buffer = new byte[10240];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                String jsonString = baos.toString();
                baos.close();
                is.close();
                JSONObject jsonArray = JSONObject.parseObject(jsonString);
                return jsonArray;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }


}
